<?php

namespace app\admin\model;

use app\common\model\MoneyLog;
use think\Model;


class Withdraw extends Model
{

    

    

    // 表名
    protected $name = 'withdraw';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'create_time_text'
    ];
    
    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            $orgin = $row->getOriginData();
            
            if ($changed['status'] == 1) {#如果是拒绝，就要把余额还回去
                 $user = User::find($orgin['user_id']);
                 $user->money = $user->money + $row['money'];
                 $user->save();
                 #记录到钱记录表中
                 MoneyLog::addMoney($orgin['user_id'],$row['money'],'提现被拒，余额返回');
                 
            }
            $row->admin_id = session('admin.id');
               
        });
    }
    
    public function getStatusList()
    {
        return ['0' => '待审核', '1' => '拒绝', '2' => '通过'];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['create_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
